#!/bin/bash

function get_Panel(){
	Panel_num=`$Login_Mysql "select type,count(1) from data_visualization_info where node_type='leaf'   and delete_flag=0  GROUP BY type;"  2>&1 |grep -v "Warning" |grep -v "count"| awk  'BEGIN {OFS=",,"} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`
	for i in $Panel_num; do
	echo "$Check_date,$Customer,看板,$i" >> $RESULTFILE
	done

	panel_sum=`$Login_Mysql "select count(1) dashboard_num from data_visualization_info where node_type='leaf' and type='dashboard' and delete_flag=0"  2>&1 |grep -v "Warning" |grep -v "dashboard_num" `
	sed -i "s/\$panel_sum/$panel_sum/g" $html_report
	datav_sum=`$Login_Mysql "select count(1) dashboard_num from data_visualization_info where node_type='leaf' and type='dataV' and delete_flag=0"  2>&1 |grep -v "Warning" |grep -v "num" `
	sed -i "s/\$datav_sum/$datav_sum/g" $html_report
	
	

}

function get_mobile(){
	mobile_num=`$Login_Mysql "select count(1) from data_visualization_info where node_type='leaf'   and delete_flag=0 and mobile_layout =1"  2>&1 |grep -v "Warning" |grep -v count`
	echo "$Check_date,$Customer,单一指标,移动端仪表板,,$mobile_num" >> $RESULTFILE

	mobile_sum=`$Login_Mysql "select count(1) mobile_num from data_visualization_info where node_type='leaf' and delete_flag=0 and mobile_layout=1" 2>&1 |grep -v "Warning" |grep -v "mobile_num" `
	sed -i "s/\$mobile_sum/$mobile_sum/g" $html_report
}

function get_Share_Link(){
	link_num=`$Login_Mysql "select count(1) from data_visualization_info where node_type='leaf'   and delete_flag=0 and mobile_layout =1"  2>&1 |grep -v "Warning" |grep -v count`
	echo "$Check_date,$Customer,单一指标,公共连接数,,$link_num" >> $RESULTFILE
	
	link_sum=`$Login_Mysql "SELECT count( 1 ) shareLink_num FROM data_visualization_info dvi INNER JOIN xpack_share xs ON dvi.id = xs.resource_id WHERE dvi.node_type = 'leaf' AND dvi.delete_flag = 0 AND xs.exp IS NULL OR xs.exp > UNIX_TIMESTAMP() * 1000 " 2>&1 |grep -v "Warning" |grep -v "shareLink_num" `
	sed -i "s/\$link_sum/$link_sum/g" $html_report
}

function get_Dataset(){
	Dataset_num=`$Login_Mysql "SELECT CASE WHEN type IS NULL AND table_name LIKE 'excel_%' THEN 'excel'  WHEN type IS NULL AND table_name LIKE 'api_%' THEN 'api'  ELSE type  END AS new_type, COUNT(1) FROM core_dataset_table WHERE table_name NOT IN ('demo_tea_material', 'demo_tea_order') GROUP BY  CASE   WHEN type IS NULL AND table_name LIKE 'excel_%' THEN 'excel'  WHEN type IS NULL AND table_name LIKE 'api_%' THEN 'api'   ELSE type  END;" 2>&1 |grep -v "Warning" |grep -v "COUNT"| awk  'BEGIN {OFS=",,"} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`

	for i in $Dataset_num; do
		echo "$Check_date,$Customer,数据集,$i" >> $RESULTFILE
	done

	Dataset_sum=`$Login_Mysql "SELECT CASE WHEN type IS NULL AND table_name LIKE 'excel_%' THEN 'excel'  WHEN type IS NULL AND table_name LIKE 'api_%' THEN 'api'  ELSE type  END AS 数据集类型, COUNT(1) 数量 FROM core_dataset_table WHERE table_name NOT IN ('demo_tea_material', 'demo_tea_order') GROUP BY  CASE   WHEN type IS NULL AND table_name LIKE 'excel_%' THEN 'excel'  WHEN type IS NULL AND table_name LIKE 'api_%' THEN 'api'   ELSE type  END;" 2>&1 |grep -v "Warning" `
	Dataset_sum2=$(printf '%q' "$Dataset_sum")
	sed -i "s#\$Dataset_sum2#$Dataset_sum2#g" $html_report


	zombie_dataset=`$Login_Mysql "SELECT id dataser_id, name dataset_name FROM core_dataset_group cdg WHERE cdg.node_type!= 'folder' AND NOT EXISTS (    SELECT 1  FROM (   SELECT table_id   FROM core_chart_view     GROUP BY table_id ) AS ccv_subquery    WHERE ccv_subquery.table_id = cdg.id  );" 2>&1 |grep -v 'Warning'`
	zombie_dataset2=$(printf '%q' "$zombie_dataset")
	sed -i "s#\$zombie_dataset2#$zombie_dataset2#g" $html_report
}

function get_DataSource(){
 	DataSource_num=`$Login_Mysql "SELECT type,count(1) from core_datasource where type <> 'folder' GROUP BY type" 2>&1 |grep -v "Warning" |grep -v "count"| awk  'BEGIN {OFS=",,"} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`

	for i in $DataSource_num; do		
		echo "$Check_date,$Customer,数据源,$i" >> $RESULTFILE
	done
	DataSource_sum=`$Login_Mysql "SELECT type 数据源类型,count(1) 数量 from core_datasource where type <> 'folder' GROUP BY type" 2>&1 |grep -v "Warning" `
	DataSource_sum2=$(printf '%q' "$DataSource_sum")
	sed -i "s/\$DataSource_sum2/$DataSource_sum2/g" $html_report


	datasource_top8=`$Login_Mysql "SELECT cd.id 数据源ID, cd.name 数据源名称, count(1) 创建数据集数, cd.type 数据源类型 FROM core_dataset_table cdt left join core_datasource cd on cdt.datasource_id = cd.id where cd.id is not null GROUP BY cd.id ORDER BY 创建数据集数 desc limit 8" 2>&1 | grep -v Warning`
	datasource_top82=$(printf '%q' "$datasource_top8")
	sed -i "s#\$datasource_top82#$datasource_top82#g" $html_report
	
	}

function get_chart_number(){
	chart_num=`$Login_Mysql "select type,count(1) from core_chart_view GROUP BY type" 2>&1 |grep -v "Warning" |grep -v "count"| awk  'BEGIN {OFS=",,"} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`
	for i in $chart_num; do
		echo "$Check_date,$Customer,图表,$i" >> $RESULTFILE
	done	

	chart_sum=`$Login_Mysql "select type,count(1) from core_chart_view GROUP BY type" 2>&1 |grep -v "Warning" `
	chart_sum2=$(printf '%q' "$chart_sum")
	sed -i "s#\$chart_sum2#$chart_sum2#g" $html_report

}

function get_Sync_task(){
	task_num=`$Login_Mysql "SELECT REPLACE(JSON_EXTRACT(parameter, '\$.source.type'), '\"', '') AS source_type, count(1) FROM per_sync_task_info GROUP BY REPLACE(JSON_EXTRACT(parameter, '\$.source.type'), '\"', '');" 2>&1 |grep -v "Warning" |grep -v "count"| awk  'BEGIN {OFS=","} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`
	for i in $get_Sync_task; do
		echo "$Check_date,$Customer,定时同步任务数,,$i" >> $RESULTFILE
	done
}

function get_UsersType(){
	user_num=`$Login_Mysql "select case origin  when 0 then 'Local'  when 1 then 'LDAP' when 2 then 'OIDC' when 3 then 'CAS' when 4 then '飞书' when 5 then ' 钉钉' when  6 then ' 企业微信' when  7 then ' 国际飞书' else 'Other' end user_source , count(1) from per_user  GROUP BY origin" 2>&1 |grep -v "Warning" |grep -v "count"| awk  'BEGIN {OFS=",,"} NF > 1 {gsub(/^[ \t]+/, "", $2); print $1,$2}'`
	for i in $user_num;
	do
		echo "$Check_date,$Customer,用户数,$i" >> $RESULTFILE
	done
	#用户数
	user_all=`$Login_Mysql "select count(1) user_num from per_user" 2>&1 |grep -v "Warning" |grep -v "user_num"`
	sed -i "s#\$user_all#$user_all#g" $html_report

	#30day 活跃用户数占比
	user_login_ratio=`$Login_Mysql "SELECT (SELECT COUNT(DISTINCT name) FROM (SELECT resource_id, name   FROM xpack_log   WHERE op = 14   AND st = 5  AND resource_id != '-1'   AND create_time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) * 1000    ) AS logged_users) /     (SELECT COUNT(DISTINCT name) FROM per_user) AS login_ratio;"  2>&1 |grep -v "Warning" |grep -v "login" `
	user_login_tmp=$( bc <<<  "$user_login_ratio * 100") 
	user_login_percentage=$(printf "%.2f%%" $user_login_tmp)
	sed -i "s/\$user_login_percentage/$user_login_percentage/g" $html_report

	
		
}


function get_Timed_Reports(){
	reports_num=`$Login_Mysql "select count(1) from xpack_report_task;" 2>&1|grep -v "Warning"|tail -1`
	echo "$Check_date,$Customer,单一指标,定时报告任务数,,$reports_num" >> $RESULTFILE

	sed -i "s/\$reports_num/$reports_num/g" $html_report
}

function get_filling_Reports(){
	filling_num=`$Login_Mysql "select count(1) from per_data_filling;" 2>&1|grep -v "Warning"|tail -1`
	echo "$Check_date,$Customer,单一指标,数据填报任务数,,$filling_num" >> $RESULTFILE

	sed -i "s/\$filling_num/$filling_num/g" $html_report
}

function get_Login_System_30day(){
	login_num=`$Login_Mysql "select count(1) login_num  from xpack_log where op=14 and st=5 and create_time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY) * 1000);" 2>&1|grep -v "Warning"|tail -1`
	echo "$Check_date,$Customer,单一指标,系统登录次数by30d,,$login_num" >> $RESULTFILE
	sed -i "s/\$login_num/$login_num/g" $html_report
}

function get_Add_Dataset_30day(){
	add_dataset=`$Login_Mysql "select  count(1) from core_dataset_group where node_type='dataset' and substr( from_unixtime( create_time / 1000 ), 1, 10 )  >= DATE_SUB(NOW(), INTERVAL 30 DAY) " 2>&1|grep -v "Warning"|tail -1`
	echo "$Check_date,$Customer,单一指标,数据集新增数by30d,,$add_dataset" >> $RESULTFILE

	sed -i "s/\$add_dataset/$add_dataset/g" $html_report
}

function get_Add_Panel_30day(){
	add_panel=`$Login_Mysql "select count(1) from data_visualization_info where node_type='leaf' and substr( from_unixtime( create_time / 1000 ), 1, 10 )  >= DATE_SUB(NOW(), INTERVAL 30 DAY)" 2>&1|grep -v "Warnging"|tail -1`
	echo "$Check_date,$Customer,单一指标,仪表板新增数by30d,,$add_panel" >> $RESULTFILE

	sed -i "s/\$add_panel/$add_panel/g" $html_report
}

function get_View_Panel_30day(){
	view_panel=`$Login_Mysql "select count(1)  from xpack_log where  op=4  and st in (1,2,9)  and substr( from_unixtime( create_time / 1000 ), 1, 10 )  >= DATE_SUB(NOW(), INTERVAL 30 DAY)" 2>&1|grep -v "Warnging"|tail -1`
	echo "$Check_date,$Customer,单一指标,仪表板查看次数by30d,,$view_panel" >> $RESULTFILE

	sed -i "s/\$view_panel/$view_panel/g" $html_report

}

function get_Edit_Panel_30day(){
	edit_panel=`$Login_Mysql "select count(1)  from xpack_log where op=2 and st in (1,2)  and substr( from_unixtime( create_time / 1000 ), 1, 10 )  >= DATE_SUB(NOW(), INTERVAL 30 DAY)" 2>&1 |grep -v "Warnging" |tail -1`
	echo "$Check_date,$Customer,单一指标,仪表板编辑次数by30d,,$edit_panel" >> $RESULTFILE

	sed -i "s/\$edit_panel/$edit_panel/g" $html_report
}

function get_ExportData_task_30day(){
	export_num=`$Login_Mysql " SELECT  COUNT(1) AS export_num FROM   core_export_task  WHERE  export_time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) * 1000 ;" 2>&1|grep -v Warning|tail -1`
	echo "$Check_date,$Customer,单一指标,30day下载数据任务数,,$export_num" >> $RESULTFILE

	sed -i "s/\$export_num/$export_num/g" $html_report
}

function get_OS_Version(){
		echo "----------------------------------------------------------"
        echo ""
        echo "######  检查系统版本  ######"
        if [[ -f /etc/redhat-release ]]; then
               os_release=`cat /etc/redhat-release`
        elif [[ -f /etc/lsb-release ]]; then
                source /etc/lsb-release
                os_release=`echo $DISTRIB_DESCRIPTION`
        else
                os_release=`echo "Other System."`
        fi
		echo $os_release
		sed -i "s/\$os_release/$os_release/g" $html_report
}
 
function get_Cpu_Status(){
        echo ""
        echo "######  检查 CPU 状态  ######"
        Physical_CPUs=$(grep "physical id" /proc/cpuinfo| sort | uniq | wc -l)
        Virt_CPUs=$(grep "processor" /proc/cpuinfo | wc -l)
        CPU_Kernels=$(grep "cores" /proc/cpuinfo|uniq| awk -F ': ' '{print $2}')
        CPU_Type=$(grep "model name" /proc/cpuinfo | awk -F ': ' '{print $2}' | sort | uniq)
        CPU_Arch=$(uname -m)
        echo "物理CPU个数:$Physical_CPUs"
        echo "逻辑CPU个数:$Virt_CPUs"
        echo "每CPU核心数:$CPU_Kernels"
        echo "CPU型号:$CPU_Type"
        echo "CPU架构:$CPU_Arch"

		sed -i "s/\$Physical_CPUs/$Physical_CPUs/g" $html_report
		sed -i "s/\$Virt_CPUs/$Virt_CPUs/g" $html_report
		sed -i "s/\$CPU_Kernels/$CPU_Kernels/g" $html_report
		sed -i "s/\$CPU_Type/$CPU_Type/g" $html_report
		sed -i "s/\$CPU_Arch/$CPU_Arch/g" $html_report
}
 
function get_System_Status(){
        echo ""
        echo "######  检查系统状态  ######"
        if [ -e /etc/sysconfig/i18n ];then
                default_LANG="$(grep "LANG=" /etc/sysconfig/i18n | grep -v "^#" | awk -F '"' '{print $2}')"
        else
                default_LANG=$LANG
        fi
        export LANG="en_US.UTF-8"
        Kernel=$(uname -r)
        OS=$(uname -o)
        Hostname=$(uname -n)
        LastReboot=$(who -b | awk '{print $3,$4}')
        uptime=$(uptime|awk '{print $3,$4}')
        xunihua=$(systemd-detect-virt)
		current_time=$(date +'%F %T')
        echo "系统：$OS"
        echo "内核：$Kernel"
        echo "主机名：$Hostname"
        echo "语言/编码：$default_LANG"
        echo "当前时间：$current_time"
        echo "最后启动：$LastReboot"
        echo "运行时间：$uptime"
        echo "虚拟化平台：$xunihua"

		sed -i "s#\$OS#$OS#g" $html_report
		sed -i "s/\$Kernel/$Kernel/g" $html_report
		sed -i "s/\$Hostname/$Hostname/g" $html_report
		sed -i "s/\$default_LANG/$default_LANG/g" $html_report
		sed -i "s/\$current_time/$current_time/g" $html_report
		sed -i "s/\$LastReboot/$LastReboot/g" $html_report
		sed -i "s/\$uptime/$uptime/g" $html_report
		sed -i "s/\$xunihua/$xunihua/g" $html_report
}
 
function get_Memory(){
        echo " "
        echo '######  检查内存空间  ######'
        mem_used=$(free -h | awk 'NR==2{printf "%.2f%%\n", $3/$2*100}')
        mem_all=$(free -h |awk 'NR==2{print $2}')
        chk_memory="总内存:  $mem_all  内存使用率:  $mem_used"
		echo $chk_memory
		memory_ratio="${chk_memory}"
		sed -i "s/\$chk_memory/$memory_ratio/g" $html_report
		mem_used_value=$(echo $mem_used | sed 's/%//g')

		if (( $(bc <<< "$mem_used_value > 80") )); then
			sed -i "s#memory_out_check#· 内存使用率已超过80%，建议持续关注，并增加内存资源；#g" $html_report
		else
			sed -i "s#memory_out_check##g" $html_report
		fi


}	
 
function get_Disk(){
        echo ""
        echo "######  检查磁盘空间  ######"
		disk_usage=$(df -h|grep /dev)
		escaped_disk_usage=$(printf '%q' "$disk_usage")
		sed -i "s#\$disk_usage#$escaped_disk_usage#g" $html_report


}

function get_Container(){
        echo ""
        echo "######  检查容器资源  ######"
		docker stats --no-stream
        container_stats=$(docker stats --no-stream | awk 'NR==1{print "CONTAINER ID", " CPU %", "  MEM USAGE / LIMIT", " MEM %", "  NAME"};NR>1{print $1, "  ",$3, " ",$4, " ",$5, " ",$6, "  ",$7,"    ",$2}')
		
		container_satatus=$(printf '%q' "$container_stats")
		sed -i "s#\$container_satatus#$container_satatus#g" $html_report

        echo "------"
		echo "容器运行时长:"
		container_list=$(docker ps --format "{{.Names}}")
 
        for container_name in $container_list
        do
                start_time=$(docker inspect --format '{{ .State.StartedAt }}' $container_name)
                start_timestamp=$(date -d "$start_time" +%s)
                now=$(date +%s)
                runtime=$((now - start_timestamp))
 
                days=$((runtime/86400))
                hours=$((runtime/3600%24))
                minutes=$((runtime/60%60))
                seconds=$((runtime%60))
 
                for_container="容器 $container_name 的运行时长为：$days 天 $hours 小时 $minutes 分钟 $seconds 秒"
				echo $for_container
				
        done
		
        echo "------"

 
        Check_Not_Run_num=$(docker ps -a --format "{{.ID}} {{.Names}} {{.Status}}"|grep Exited|wc -l)
        if [ $Check_Not_Run_num = "0" ]; then
                con_stop="不存在停止状态的容器"
				echo $con_stop
				sed -i "s#\$container_txt_info#$con_stop#g" $html_report
				sed -i "s#stop_contain_check##g" $html_report
        else
                echo "存在停止运行的容器:"
                for Not_Run_ID in $(docker ps -a --format "{{.ID}} {{.Names}} {{.Status}}"|grep Exited|awk '{print $1}')
                do
                        Not_Run_Name=$(docker ps -a --format "{{.ID}} {{.Names}}"|grep $Not_Run_ID|awk '{print $2}')
                        container_stop="容器名: $Not_Run_Name                容器ID: $Not_Run_ID"
						echo  $container_stop
						echo  $container_stop >> .container_stop
                done
				container_stop_txt=`cat .container_stop`
				container_txt_info=$(printf '%q' "$container_stop_txt")
				sed -i "s#\$container_txt_info#$container_txt_info#g" $html_report
				sed -i "s#stop_contain_check#· 服务器存在停止运行的容器，请检查容器进程，确认是否为计划设定状态；#g" $html_report
				rm -f .container_stop
				

        fi
}
 
function get_DE_Version(){
        echo ""
        echo "######  检查 DataEase 版本  ######"
        de_version=`dectl version`
		echo $de_version
		de_version2=$(printf '%q' "$de_version")
		sed -i "s#\$de_version2#$de_version2#g" $html_report
}
 
function get_MySQL_Mode(){
        echo ""
        echo "######  检查 MySQL 安装模式  ######"

        MySQL_External=$(grep 'DE_EXTERNAL_MYSQL=' $Install_Folder/dataease2.0/.env |awk -F '=' '{print $2}')

        if [ $MySQL_External = true ]; then
                mysql_mod="MySQL 外置部署"
				echo $mysql_mod
				sed -i "s#\$mysql_mod#$mysql_mod#g" $html_report
		else 
				mysql_mod="使用内置 MySQL"
				echo=$mysql_mod
				sed -i "s#\$mysql_mod#$mysql_mod#g" $html_report
        fi
}

function Check_Backup(){
	echo ""
	echo "######  检查备份状态  ######"
	yesterday=$(date -d "yesterday" +%Y_%m_%d)
	today=$(date +%Y_%m_%d)

	crontab -l|grep backup-de.sh >/dev/null 2>&1
	present_cron=$(echo $?)
	if [ "$present_cron" = "0" ]; then
		echo "crontab 中检测到备份任务: `crontab -l|grep backup-de.sh`"
		backup_file=`crontab -l | grep "backup-de.sh" | sed 's/.* \([^ ]*\)$/\1/'`
		if [ -f "$backup_file" ]; then
			echo "检测到备份脚本文件: $backup_file"
			sed -i "s#bak_task_output##g" $html_report
			bak_dir=$(cat $backup_file |grep BAK_DIR=|awk -F '=' '{print $2}')
			if [ -n "$(find $bak_dir -maxdepth 1 -name "dataease_${yesterday}*")" -o -n "$(find $bak_dir -maxdepth 1 -name "dataease_${today}*")" ]; then
				retention_day=$(cat $backup_file |grep find|awk '{print $4}'|sed 's/[^0-9]//g'|head -1)
				echo "备份正常进行中;"
				echo "最近的目录备份是："$(ls -lrt $bak_dir/dataease_* |grep -v "总用量"|awk '{print $9}'|tail -1)
				if [ -n "$(find $bak_dir -maxdepth 1 -type f -name 'mysql-dataease_*' -exec stat --format='%Y %n' {} \; | sort -n | tail -1 | awk '{print $2}')" ]; then
					echo "最近的 SQL 数据备份是："$(ls -lrt $bak_dir/mysql-dataease_* |grep -v "总用量"|awk '{print $9}'|tail -1)
				else
					echo "SQL 数据备份不存在！"
				fi
				if [ -n "$(find $bak_dir -maxdepth 1 -type f -name 'mysql-function_*' -exec stat --format='%Y %n' {} \; | sort -n | tail -1 | awk '{print $2}')" ]; then
					echo "最近的 Function 备份是：" $(ls -lrt $bak_dir/mysql-function_* |grep -v "总用量"|awk '{print $9}'|tail -1)
				else
					echo "Function 备份不存在！"
				fi
				echo "备份保留天数："$retention_day 天
				echo "实际备份存在：" $(ls -lrt $bak_dir/dataease_*|wc -l) 天
				echo "备份目录占磁盘空间："$(du -sh $bak_dir|awk '{print $1}')
				echo "备份目录可用空间：" $(df -h $bak_dir|tail -1|awk '{print $4}')
			else	
				echo "但是，近两天没有备份文件！"
			fi
		else 
			echo "但是，未检测到备份脚本文件！"
		fi
	else 
		bak_status="crontab 中未检测到备份任务！"
		echo $bak_status
		sed -i "s#\$bak_status#$bak_status#g" $html_report
		sed -i "s#bak_task_output#· 巡检过程未发现备份任务，请创建 DataEase 备份任务；#g" $html_report
	fi
}

function Check_https(){
	echo ""
	echo "######  检查 HTTPS  ######"
	PROTOCOLS=$(echo | openssl s_client -connect "127.0.0.1:443" 2>&1)

	if echo "${PROTOCOLS}" | grep "errno"; then
		https_status="服务器没有检测到 HTTPS !"
		echo $https_status
		sed -i "s#\$https_status#$https_status#g" $html_report
		sed -i "s#· SSL证书#检测到未配置 HTTPS, 建议启用 http2；#g" $html_report
	else
		https_status="已在服务器配置 HTTPS."
		sed -i "s#SSL证书##g" $html_report
		echo $https_status
		sed -i "s#\$https_status#$https_status#g" $html_report
		PROTOCOLS=$(echo -n | openssl s_client -alpn 'h2' -connect "127.0.0.1:443" 2>&1)

		if echo "${PROTOCOLS}" | grep -q "ALPN protocol: h2"; then
			http2_status="已启用 HTTP/2."
			echo $http2_status
			sed -i "s#\$http2_status#$http2_status#g" $html_report
		else
			http2_status="没有启用 HTTP/2 !"
			echo $http2_status
			sed -i "s#\$http2_status#$http2_status#g" $html_report

	fi
	fi
	echo " "

}


function Check_kuayuan(){
	echo ""
	echo "######  检查 跨源数据集  ######"
	#获取数据集 info
	dataset_info=$($Login_Mysql "SELECT info FROM core_dataset_group where node_type='dataset' " 2>&1 | grep -v "Warning"  )
	#填报的数据源id
	tianbao_source_id=$($Login_Mysql  "SELECT datasource FROM per_data_filling where node_type='form' " 2>&1 | grep -v "Warning" )
	#数据源id
	data_source_id=$($Login_Mysql  "select id from core_datasource" 2>&1 | grep -v "Warning"|grep -v id|sort |uniq)
	#同步库 source id
	sync_source_id=$($Login_Mysql  "SELECT cd_subquery.id FROM ( SELECT JSON_EXTRACT(configuration, '$.host') AS host_psd FROM per_sync_datasource psd where type='doris') AS psd_subquery LEFT JOIN (SELECT cd.id, JSON_EXTRACT(configuration, '$.host') AS host_cd FROM core_datasource cd WHERE type='doris' and configuration LIKE '{%') AS cd_subquery ON psd_subquery.host_psd = cd_subquery.host_cd GROUP BY cd_subquery.id" 2>&1 | grep -v "Warning"|grep -v id|grep -v 'NULL')
	#业务库 source id
	yewu_source_id=$($Login_Mysql  "( SELECT	cd.id 	FROM	core_datasource cd 	WHERE	cd.type = 'doris' 	AND cd.configuration LIKE '{%' 	AND NOT EXISTS ( SELECT 1 FROM per_sync_datasource psd WHERE psd.type = 'doris' AND JSON_EXTRACT( psd.configuration, '$.host' ) = JSON_EXTRACT( cd.configuration, '$.host' ) ) ) UNION ALL (	SELECT	cd.id 	FROM	core_datasource cd WHERE	cd.type != 'doris')" 2>&1 | grep -v "Warning"|grep -v id)

	#跨源数据集数
	kuayuan_dataset=0
	#填报源统计
	tianbao_num=0
	#同步源统计
	tongbu_num=0
	#业务源统计
	yewu_num=0

	#逐条裁剪
	for dataset_line in $dataset_info; do

		#数据集的数据源id
		datasorce_id_output=$(echo $dataset_line |  grep -oE '"datasourceId":"([^"]+)"' | grep -oE '([^"]+)'|grep -v 'datasourceId' |grep -v ':' | sort| uniq)
		
		# 计算输出的行数
		num_lines=$(echo "$datasorce_id_output" | wc -l)
		#大于1则是跨源
		if [ $num_lines -gt 1 ]; then
			#跨源数据集记录+1
			(( kuayuan_dataset = kuayuan_dataset + 1))
			
			for dataset_datasorce_id in $datasorce_id_output; do

				#对比填报表source ID
				for tianbao in $tianbao_source_id; do
					if [[ $dataset_datasorce_id == $tianbao ]]; then
						((tianbao_num = tianbao_num + 1))
					fi   
				done

				#对比同步库
				for datasource_info in $sync_source_id; do
					if [[ $dataset_datasorce_id == $datasource_info ]]; then
						((tongbu_num = tongbu_num + 1))
					fi
				done

				#对比业务库
				for yewu_source in $yewu_source_id; do
					if [[ $dataset_datasorce_id == $yewu_source ]]; then
						((yewu_num = yewu_num + 1))
						break;
					fi
				done
			done
		fi
	done

	(( yewu_num = kuayuan_dataset  - tianbao_num - tongbu_num ))

	if [[ $kuayuan_dataset > 0 ]]; then
		echo "跨源数据集有 $kuayuan_dataset 个"
		sed -i "s/\$kuayuan_dataset/$kuayuan_dataset/g" $html_report
		if [[ $tianbao_num > 0 ]]; then
			echo "其中有 $tianbao_num 个数据集使用 数据填报源" 
		fi
		if [[ $tongbu_num > 0 ]]; then
			echo "其中有 $tongbu_num 个数据集使用 数据同步源"
		fi
		if [[ $yewu_num > 0 ]]; then
			echo "其中有 $yewu_num 个数据集使用 业务数据源"
		fi   
	else    echo "没有使用跨源关联数据集。"
	fi

}


function check-resource(){
	echo "DataEase资源检测 ..."
	Total=0
	Set=5
	get_Panel
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_mobile
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Share_Link
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Dataset
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_DataSource
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_chart_number
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Sync_task
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_UsersType
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Timed_Reports
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_filling_Reports
	((Total+=Set))
	printf "已完成：$Total %%\r"

	get_Login_System_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Add_Dataset_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Add_Panel_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_View_Panel_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Edit_Panel_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 
	
	get_ExportData_task_30day
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	echo "检查结果保存于当前目录：$RESULTFILE"
}



function check-system(){
	echo "服务系统资源检测 ..."
	Total=0
	Set=7
	get_OS_Version  >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Cpu_Status  >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_System_Status  >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Memory  >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Disk >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_Container >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_DE_Version >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	get_MySQL_Mode >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	Check_Backup >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	Check_https >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 

	Check_kuayuan >> $RESULTTEXT
	((Total+=Set))
	printf "已完成：$Total %%\r" 
	
	echo "检查结果保存于当前目录：$RESULTTEXT"
}

echo "正在初始化脚本..."

Install_Folder=$(grep "DE_BASE=" /usr/bin/dectl |awk -F '=' '{print $2}')
MySQL_Host=$(grep "DE_MYSQL_HOST=" $Install_Folder/dataease2.0/.env|awk  -F '=' '{print $2}')
MySQL_User=$(grep "DE_MYSQL_USER=" $Install_Folder/dataease2.0/.env|awk  -F '=' '{print $2}')
MySQL_Password=$(grep "DE_MYSQL_PASSWORD=" $Install_Folder/dataease2.0/.env|awk  -F '=' '{print $2}')
MySQL_DB=$(grep "DE_MYSQL_DB=" $Install_Folder/dataease2.0/.env|awk  -F '=' '{print $2}')
MySQL_Port=$(grep "DE_MYSQL_PORT=" $Install_Folder/dataease2.0/.env|awk  -F '=' '{print $2}')

DE_MySQL_Name=$(dectl status|grep mysql|awk '{print $1}')

if [ "$MySQL_Host" = "$DE_MySQL_Name" ];then
	Login_Mysql="docker exec  $MySQL_Host mysql -u$MySQL_User -p$MySQL_Password $MySQL_DB -e"
else
	chmod +x ./tools/mysql
	Login_Mysql="./tools/mysql -h$MySQL_Host -u$MySQL_User -p$MySQL_Password  -P$MySQL_Port $MySQL_DB  -e"
fi

RESULTFILE="CheckResult-`date +%Y%m%d`.csv"
RESULTTEXT="CheckResult-`date +%Y%m%d`.txt"
echo > $RESULTTEXT

Customer=$($Login_Mysql "select f2c_license from license" 2>&1|grep -v "Using a password on the command line interface can be insecure"|awk -F '\"' '{print $14}' |tail -1)
Check_date=$(date "+%Y-%m-%d")

[ $(id -u) -gt 0 ] && echo "请使用 root 用户运行该脚本" && exit 1

echo "巡检时间,客户名称,检查类别,维度,来源,数量" > $RESULTFILE

html_report="CheckResult-DataEase巡检报告_$(date +%Y%m%d).html"
cp ./tools/DataEase巡检报告模版.html $html_report
sed -i "s/\$Customer/$Customer/g" $html_report

check-resource
check-system